<?
/*
* Usage:

require_once("SearchQuery.php");
$squery = new SearchQuery();
$squery->table = "t";                           // Sets the table
$squery->setFields(array("name", "email"));     // Setting up search fields
$squery->setQueryString($_GET['search']);       // Or $queryString or whatever your string publiciable is
$squery->isExact = false;                       // if false, SearchQuery searchs like '%$query%', else '$query'
$whereCondition = $squery->build();             // returns "(name LIKE '$string') OR (email LIKE '$string'" etc...

*/

class SearchQuery
{
    // PUBLIC
    public $table = '';
	public $arFields = array();
	public $queryString = '';
	public $disableWildCard = false;
	public $isExact = false; // if true, searchs like '%$query%', else '$query'

	// PRIVATE
	public $_arEntities = array();
	public $_strSoup = "";
	public $_minNumOfCharsPerWord = 2;


	// constructor
	public function __construct() {}

	public function build()
	{
		$this->_getEncapsulated();
		if ($this->queryString=='') return 0;

		foreach($this->arFields AS $field)
		{
			$sql .= " ( ";
			$arSQL = array();
			reset($this->_arEntities);
			foreach($this->_arEntities AS $entity)
			{
			    $entity = mysql_escape_string($entity);
				array_push($arSQL, ($this->table? $this->table ."." : "" ). $field ." LIKE '". ($isExact? $entity : "%". $entity ."%" ) ."'");
			}
			$sql .= implode(" OR ", $arSQL);
			$sql .= " ) OR ";
		}
		return substr($sql, 0, strlen($sql)-3);
	}


	// SETTERS
	public function setFields($fields)
	{
		$this->arFields = $fields;
	}


	public function setQueryString($string)
	{
		$this->queryString = $string;
	}


	// Private functions
	public function _getEncapsulated()
	{
		if ($this->queryString=='') return;
		// Clean up Query String
		$queryString = stripslashes(trim($this->queryString));
		if ($this->disableWildCard==false) $queryString = str_replace("%", "\%", $this->queryString);

		// Look up for "" matches
		preg_match_all("/\"(.*?)\"/s", $queryString, $matches, PREG_SET_ORDER);
		foreach($matches AS $tmp)
		{
			array_push($this->_arEntities, $tmp[1]);
		}

		// Look up for single words
		$words = trim(preg_replace("/\"(.*?)\"/s", '', $queryString));
		$singleWords = preg_split('/(\s+)/', $words);
		foreach($singleWords AS $word)
		{
			if (strlen($word)>=$this->_minNumOfCharsPerWord) array_push($this->_arEntities, $word);
            else $this->_strSoup .= $word;
		}
		if ($this->_strSoup != "")
		    array_push($this->_arEntities, $this->_strSoup);
	}

}
?>